今天要使用 D3 客製化直條圖,學習畫一張直條圖需要由哪些部分組成。
下載鯖魚價格的 csv 檔案

markerel_bars = {
  
  const container = html `<svg width="900" height="500"/>` // 圖片大小
  
  const svg = d3.select(container)
  // 直條圖
  svg.append('g')
    .attr('class', 'bars')
    .selectAll('rect')
    .data( mackerel_price2 )
    .join('rect')
      .attr('class', 'bar')
      .attr('x', d => xScale(d.市場))
      .attr('y', d => yScale(d.平均價))
      .attr('width', xScale.bandwidth()) // bandwidth() 會回傳直條圖的寬度
      .attr('height', d => yScale(0) - yScale(d.平均價)) // yScale(0) 是全部高度
      .style('fill', 'steelblue')
  
  // x 軸
  svg.append('g')
      .attr('class', 'x-axis')
      .attr('transform', `translate(0,${ height - margin.bottom })`)
      .call( xAxis )
      .style("font-size", 14)
  // y 軸
  svg.append('g')
      .attr('class', 'y-axis')
      .attr('transform', `translate(${ margin.left },0)`)
      .call( yAxis )
      .style("font-size", 14)
  // x 軸標示文字
  svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height)
    .attr("dy", "-0.5em")
    .text("市場")
  // y 軸標示文字
  svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("transform", "rotate(-90)")
    .attr("x", -200)
    .attr("y", margin.left)
    .attr("dy", "-2em")
    .text("平均價(元/公斤)")
  
  return container
  
}
相較於【Day 2】是引用別人寫好的程式碼,今天是一步一步地把構成直條圖的部分組合起來,好處是可以根據需求自由地加入想要的東西,有更多的彈性。